﻿using System;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using Framework;

namespace Enterprise
{
    /// <summary>
    /// 照片管理
    /// </summary>
    public class PhotoService : BaseService
    {
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="albumid"></param>
        /// <param name="name"></param>
        /// <param name="nameEn"></param>
        /// <param name="description"></param>
        /// <param name="descriptionEn"></param>
        /// <param name="type"> </param>
        /// <param name="sort"></param>
        /// <param name="isCover"> </param>
        /// <param name="filedata"></param>
        /// <param name="businessCardCategoryId"> </param>
        /// <returns></returns>
        public string[] Add(int albumid = 0, string name = "", string nameEn = "", string description = "", string descriptionEn = "", int type = 0, int sort = 0, bool isCover = false, HttpPostedFileBase filedata = null, int businessCardCategoryId = 0)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "图片名称");
            Check.Argument.IsNotOutOfLength(nameEn, 50, "图片名称(En)");
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = PhotoConfig.RelativePath,
                    IsAdaptive = PhotoConfig.IsAdaptive,
                    IsImage = true,
                    IsGenerateThumbnail = PhotoConfig.IsGenerateThumbnail,
                    FileMaxLength = PhotoConfig.ImageSize,
                    ThumbnailHeight = PhotoConfig.ThumbnailHeight,
                    ThumbnailWidth = PhotoConfig.ThumbnailWidth,
                    ThumbnailPrefix = PhotoConfig.ThumbnailPrefix
                };
                if (!uploadHelper.Save())
                {
                    throw new Exception(uploadHelper.ErrorMessage);
                }
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var sbSql = new StringBuilder();
            sbSql.Append("insert into tbPhoto(");
            sbSql.Append("CoAlbumId,CoName,CoNameEn,CoDescription,CoDescriptionEn,CoDate,CoType,CoTypeName,CoTypeNameEn,CoUrl,CoSort,CoNormalImage,CoSmallImage,CoBigImage");
            sbSql.Append(") values(");
            sbSql.Append("@CoAlbumId,@CoName,@CoNameEn,@CoDescription,@CoDescriptionEn,@CoDate,@CoType,@CoTypeName,@CoTypeNameEn,@CoUrl,@CoSort,@CoNormalImage,@CoSmallImage,@CoBigImage");
            sbSql.Append(")");
            var parameters = new[]
                {
                    new OleDbParameter("@CoAlbumId", OleDbType.Integer),
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescription", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescriptionEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDate", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoType", OleDbType.Integer),
                    new OleDbParameter("@CoTypeName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoTypeNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoUrl", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSort", OleDbType.Integer),
                    new OleDbParameter("@CoNormalImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSmallImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoBigImage", OleDbType.VarChar, 255)
                };
            parameters[0].Value = albumid;
            parameters[1].Value = name;
            parameters[2].Value = nameEn;
            parameters[3].Value = description;
            parameters[4].Value = descriptionEn;
            parameters[5].Value = DateTime.Now;
            parameters[6].Value = DBNull.Value;
            parameters[7].Value = DBNull.Value;
            parameters[8].Value = DBNull.Value;
            parameters[9].Value = DBNull.Value;
            parameters[10].Value = fileName;
            parameters[11].Value = thumFileName;
            parameters[12].Value = fileName;
            var rows = DbHelperOleDb.Add(sbSql.ToString(), parameters).SafeToInt();
            if (rows > 0)
            {
                return new[] { rows.ToString(CultureInfo.InvariantCulture), fileName, thumFileName };
            }
            throw new Exception("添加失败！");
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="albumid"> </param>
        /// <param name="name"></param>
        /// <param name="nameEn"></param>
        /// <param name="description"></param>
        /// <param name="descriptionEn"></param>
        /// <param name="type"> </param>
        /// <param name="sort"></param>
        /// <param name="isCover"> </param>
        /// <param name="filedata"></param>
        /// <param name="businessCardCategoryId"></param>
        /// <returns></returns>
        public int Eidt(int id = 0, int albumid = 0, string name = "", string nameEn = "", string description = "", string descriptionEn = "", int type = 0, int sort = 0, bool isCover = false, HttpPostedFileBase filedata = null, int businessCardCategoryId = 0)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "图片名称");
            Check.Argument.IsNotOutOfLength(nameEn, 50, "图片名称(En)");
            var parameters = new[]
                {
                    new OleDbParameter("@CoAlbumId", OleDbType.Integer),
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescription", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescriptionEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDate", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoType", OleDbType.Integer),
                    new OleDbParameter("@CoTypeName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoTypeNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoUrl", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSort", OleDbType.Integer),
                    new OleDbParameter("@CoNormalImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSmallImage", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoBigImage", OleDbType.VarChar, 255)
                };
            parameters[0].Value = albumid;
            parameters[1].Value = name;
            parameters[2].Value = nameEn;
            parameters[3].Value = description;
            parameters[4].Value = descriptionEn;
            parameters[5].Value = DateTime.Now;
            parameters[6].Value = DBNull.Value;
            parameters[7].Value = DBNull.Value;
            parameters[8].Value = DBNull.Value;
            parameters[9].Value = DBNull.Value;
            var sbSql = new StringBuilder();
            sbSql.Append("update tbPhoto set ");
            sbSql.Append(" CoAlbumId=@CoAlbumId,CoName=@CoName,CoNameEn=@CoNameEn,CoDescription=@CoDescription,CoDescriptionEn=@CoDescriptionEn,CoType=@CoType,CoTypeName=@CoTypeName,CoTypeNameEn=@CoTypeNameEn,CoUrl=@CoUrl");
            if (filedata != null && filedata.ContentLength > 0)
            {
                sbSql.Append(",CoNormalImage=@CoNormalImage,CoSmallImage=@CoSmallImage,CoBigImage=@CoBigImage");

                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = PhotoConfig.RelativePath,
                    IsAdaptive = PhotoConfig.IsAdaptive,
                    IsImage = true,
                    IsGenerateThumbnail = PhotoConfig.IsGenerateThumbnail,
                    FileMaxLength = PhotoConfig.ImageSize,
                    ThumbnailHeight = PhotoConfig.ThumbnailHeight,
                    ThumbnailWidth = PhotoConfig.ThumbnailWidth,
                    ThumbnailPrefix = PhotoConfig.ThumbnailPrefix
                };
                if (!uploadHelper.Save())
                {
                    throw new Exception(uploadHelper.ErrorMessage);
                }
                var fileName = uploadHelper.FileName;
                var thumFileName = uploadHelper.ThumbnailFileName;
                parameters[10].Value = fileName;
                parameters[11].Value = thumFileName;
                parameters[12].Value = fileName;
                var path = HttpContext.Current.Server.MapPath(PhotoConfig.RelativePath);
                var ds = DbHelperOleDb.Query("select * from tbPhoto where coPhotoid={0}".FormatWith(id));
                foreach (DataRow item in ds.Tables["ds"].Rows)
                {
                    FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                    FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                    FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
                }
            }
            sbSql.AppendFormat(" where CoPhotoId={0}", id);
            var rows = DbHelperOleDb.ExecuteSql(sbSql.ToString(), parameters).SafeToInt();
            if (rows > 0)
            {
                return rows;
            }
            throw new Exception("修改失败！");
        }
        public void Delete(int id)
        {
            var path = HttpContext.Current.Server.MapPath(PhotoConfig.RelativePath);
            var ds = DbHelperOleDb.Query("select * from tbPhoto where coPhotoid={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            int rows = DbHelperOleDb.ExecuteSql("delete  from tbPhoto where coPhotoid={0}".FormatWith(id));
            if (!(rows > 0))
                throw new Exception("记录不存在！");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageValue"></param>
        /// <param name="rowsValue"></param>
        /// <param name="albumId"></param>
        /// <param name="sort"> </param>
        /// <param name="order"> </param>
        /// <returns></returns>
        public Table GetTable(string name, int pageValue, int rowsValue, int albumId = 0, string sort = "CoSort", string order = "Desc")
        {
            var sbSqlWhere = new StringBuilder();
            sbSqlWhere.Append(" where (CoName like '%'+@CoName+'%' or  CoNameEn like '%'+@CoName+'%') ");
            if (albumId != 0)
            {
                sbSqlWhere.Append(" and coalbumId=@CoAlbumId ");
            }
            var parameters = new[]
                           {
                               new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                               new OleDbParameter("@CoAlbumId", OleDbType.Integer)
                           };
            parameters[0].Value = name.SqlLike();
            parameters[1].Value = albumId;
            int total = DbHelperOleDb.GetSingle("select count(*) from TbPhoto {0}".FormatWith(sbSqlWhere), parameters).SafeToInt();
            var sqlTwo = new StringBuilder();
            sqlTwo.AppendFormat("select top {0} * from TbPhoto {1} ", rowsValue, sbSqlWhere);
            if (pageValue > 1)
                sqlTwo.AppendFormat(" and  coPhotoid not in(select top {0} coPhotoid {1} order by {2} {3},CoPhotoId desc)", rowsValue * (pageValue - 1), sbSqlWhere, sort, order);
            sqlTwo.AppendFormat(" order by {0} {1},CoPhotoId desc  ", sort, order);
            var ds = DbHelperOleDb.Query(sqlTwo.ToString(), parameters);
            return new Table { Rows = ds.Tables["ds"].Rows, Total = total };
        }
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            var rows = DbHelperOleDb.Query("select * from TbPhoto where CoPhotoId={0}".FormatWith(id)).Tables["ds"].Rows;
            return rows[0];
        }
        /// <summary>
        /// 设置封面
        /// </summary>
        /// <param name="id"></param>
        /// <param name="albumId"></param>
        public void SetCover(int id, int albumId)
        {
            var photoRows = DbHelperOleDb.Query("select * from TbPhoto where CoPhotoId={0}".FormatWith(id)).Tables["ds"].Rows;
            if (photoRows.Count > 0)
            {
                var photoRow = photoRows[0];
                var sqlList = new ArrayList
                    {
                        "update tbalbum set CoNormalImage={0},CoSmallImage={1},CoBigImage={2} from tbPhoto where coalbumid={3}".FormatWith(photoRow["CoNormalImage"], photoRow["CoSmallImage"], photoRow["CoBigImage"],albumId),
                        "update tbPhoto set coiscover=1 from tbPhoto where coPhotoid={0}".FormatWith(id),
                        "update tbPhoto set coiscover=0 from tbPhoto where coPhotoid<>{0} and coiscover=1".FormatWith(id)
                    };
                DbHelperOleDb.ExecuteSqlTran(sqlList);
            }
            else
            {
                throw new Exception("记录不存在！");
            }
        }

    }
}
